package com.base.common.util;

import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;

import com.base.common.db.DBConstants;
import com.base.common.util.log.LogUtil;

import java.lang.reflect.Field;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 *对象与ContentValue之间转换，生成SQL等
 */
public class ObjectUtil {
	private static final String TAG="ObjectUtil";
    private static Map<String, Uri> uris ;

    static {
        uris = new HashMap<String, Uri>();
        
        String protocol = DBConstants.ContentProvider.PROTOCOL;
        String authority = DBConstants.ContentProvider.AUTHORITY;
        for (String table : DBConstants.ShopDB.TABLES_STRINGS) {
            /**
             * 所有表与Uri对应关系
             */
            Uri uri = Uri.parse(protocol + authority + "/" + table);
            uris.put(table, uri);
        }
    }
    
    /**
     * <默认构造函数>
     */
    public ObjectUtil() {

    }

    public  Map<String, Uri> getUris() {
        return uris;
    }

    /**
     * <获取数据存取的Uri> <从所有表对应的URI集合中根据相应类查出对应的Uri>
     * 
     * @param cls 类对象
     * @return Uri [类对应的Uri]
     */
    public static Uri getUri(Class<?> cls) {
        String table = cls.getSimpleName();
        return uris.get(table);
    }

    /**
     * <数据结果集转换为相应的对象> <方便操作,即操作对象即可,将值都赋到对象的属性中>
     * 
     * @param cursor 结果集游标
     * @param cls 要查询返回的类对象
     * @throws IllegalArgumentException
     * @throws IllegalAccessException [参数说明]
     * @return Object [返回赋值后的对象结果]
     * @exception throws [违例类型] [违例说明]
     */
    public static Object convertCursorToObject(Cursor cursor, Class<?> cls)
            throws IllegalArgumentException, IllegalAccessException {
        Object obj = null;
        try {
            obj = cls.newInstance();
        } catch (InstantiationException e) {
            return null;
        }
        Field[] fields = cls.getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            Class<?> type = field.getType();// 属性类型
            String colName = field.getName();// 属性名
            int index = cursor.getColumnIndex(colName);// 列索引
            if (index < 0){
                continue;
            }
            if (type == Integer.class || type == int.class) {
                int colValue = cursor.getInt(index);
                field.set(obj, colValue);
            } else if (type == String.class) {
                String colValue = cursor.getString(index);
                field.set(obj, colValue);
            } else if (type == Float.class || type == float.class) {
                float colValue = cursor.getFloat(index);
                field.set(obj, colValue);
            } else if (type == Long.class || type == long.class ) {
                long colValue = cursor.getLong(index);
                field.set(obj, colValue);
            } else if (type == Double.class || type == double.class) {
                double colValue = cursor.getDouble(index);
                field.set(obj, colValue);
            } else if (type == Byte.class || type == byte.class) {
                int colValue = cursor.getInt(index);
                byte value = Byte.parseByte(colValue + "");
                field.set(obj, value);
            } else if (type == Byte[].class || type == byte[].class) {
                byte[] colValue = cursor.getBlob(index);
                field.set(obj, colValue);
            } else if (type == Short.class || type == short.class) {
                short colValue = cursor.getShort(index);
                field.set(obj, colValue);
            } else if (type == Boolean.class || type == boolean.class) {
                int colValue = cursor.getInt(index);
                Boolean value = false;
                if (colValue == 1) {
                    value = true;
                }
                field.set(obj, value);
            } else if (type == Date.class) {           
                long tempValue =cursor.getLong(index);
                //String tempValue=cursor.getString(index);
                Date value = new Date(tempValue);
                field.set(obj, value);
            }
        }
        return obj;
    }

    /**
     * <对象值转换为ContentValues> <便于数据存储,以对象方式操作数据>
     * 
     * @param obj 实例化对象,且对象的属性要赋值
     * @throws IllegalArgumentException
     * @throws IllegalAccessException [参数说明]
     * @return ContentValues [返回赋值后的ContentValues]
     * @exception throws [违例类型] [违例说明]
     */
    public static ContentValues convertObjectToContentValues(Object obj)
            throws IllegalArgumentException, IllegalAccessException {
        if (obj == null) {
            return null;
        }
        ContentValues values = new ContentValues();
        Class<?> cls = obj.getClass();
        /* 所有私有属性 */
        Field[] fields = cls.getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);// 设置私有属性可访问
            Class<?> type = field.getType();
            String key = field.getName();      
            LogUtil.i(TAG, key);
            if (type == Integer.class||type == int.class) {
                Object temp = field.get(obj);
                if (temp != null) {
                    Integer value = (Integer)temp;
                    values.put(key, value);
                }
            } else if (type == String.class) {
                Object temp = field.get(obj);
                String value = temp == null ? "" : (String)temp;
                values.put(key, value);
            } else if (type == Float.class) {
                Object temp = field.get(obj);
                if (temp != null) {
                    Float value = (Float)temp;
                    values.put(key, value);
                }
            } else if (type == Double.class) {
                Object temp = field.get(obj);
                if (temp != null) {
                    Double value = (Double)temp;
                    values.put(key, value);
                }
            } else if (type == Short.class) {
                Object temp = field.get(obj);
                if (temp != null) {
                    Short value = (Short)temp;
                    values.put(key, value);
                }
            } else if (type == Boolean.class) {
                Object temp = field.get(obj);
                if (temp != null) {
                    Boolean value = (Boolean)temp;
                    values.put(key, value);
                }
            } else if (type == Byte.class) {
                Object temp = field.get(obj);
                if (temp != null) {
                    Byte value = (Byte)temp;
                    values.put(key, value);
                }
            } else if (type == Byte[].class) {
                Object temp = field.get(obj);
                byte[] value = temp == null ? null : (byte[])temp;
                values.put(key, value);
            } else if (type == Date.class) {
                Object temp = field.get(obj);
                if (temp != null) {
                    Date tempValue = (Date)temp;
                    long value = tempValue.getTime();
                    values.put(key, value);
                }
            }            
        }

        return values;
    }

    /**
     * <生成查询的所有列> <根据类对象生成相应的查询列>
     * 
     * @param cls 要查询返回的类对象
     * @return String[] [返回查询列]
     * @exception throws [违例类型] [违例说明]
     */
    public static String[] generateQueryCols(Class<?> cls) {
        Field[] fields = cls.getDeclaredFields();
        String[] projection = new String[fields.length];
        int index = 0;
        for (Field field : fields) {
            projection[index] = field.getName();
            index++;
        }
        return projection;
    }

    /**
     * <生成查询条件> <根据条件对象生成需要查询的条件>
     * 
     * @param obj 查询对象
     * @throws IllegalArgumentException
     * @throws IllegalAccessException [参数说明]
     * @return String [返回查询条件]
     * @exception throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    public static String generateWhereSql(Object obj) throws IllegalArgumentException,
            IllegalAccessException {
        if (obj == null) {
            return null;
        }
        Class<?> cls = obj.getClass();
        StringBuffer where = new StringBuffer();
        /* 所有私有属性 */
        Field[] fields = cls.getDeclaredFields();
        
        String and = " and ";
        String eq = "=";
        for (Field field : fields) {
            field.setAccessible(true);// 设置私有属性可访问
            Class<?> type = field.getType();
            String key = field.getName();

            if (type == Integer.class) {
                Object temp = field.get(obj);
                if (temp != null) {
                    Integer value = (Integer)temp;
                    where.append(and).append(key).append(eq).append(value);
                }
            } else if (type == String.class) {
                Object temp = field.get(obj);
                String value = temp == null ? "" : (String)temp;
                if (value != null && !"".equals(value)) {
                    where.append(and + key + "='" + value + "'");
                }
            } else if (type == Float.class) {
                Object temp = field.get(obj);
                if (temp != null) {
                    Float value = (Float)temp;
                    where.append(and).append(key).append(eq).append(value);
                }
            } else if (type == Double.class) {
                Object temp = field.get(obj);
                if (temp != null) {
                    Double value = (Double)temp;
                    where.append(and).append(key).append(eq).append(value);
                }
            } else if (type == Short.class) {
                Object temp = field.get(obj);
                if (temp != null) {
                    Short value = (Short)temp;
                    where.append(and).append(key).append(eq).append(value);
                }
            } else if (type == Boolean.class) {
                Object temp = field.get(obj);
                if (temp != null) {
                    Boolean tempValue = (Boolean)temp;
                    int value = 0;
                    if (tempValue) {
                        value = 1;
                    }
                    where.append(and).append(key).append(eq).append(value);
                }
            } else if (type == Byte.class) {
                Object temp = field.get(obj);
                if (temp != null) {
                    Byte value = (Byte)temp;
                    where.append(and).append(key).append(eq).append(value);
                }
            } else if (type == Date.class) {
                Object temp = field.get(obj);
                if (temp != null) {
                    Date tempValue = (Date)temp;
                    long value = tempValue.getTime();
                    where.append(and).append(key).append(eq).append(value);
                }
            }
        }
        String where2 = where.toString();
        if (where2.startsWith(" and")) {
            where2 = where2.substring(" and".length());
        }
        return where2;
    }
}
